/*
 * SFTPConnection.cpp
 *
 *  Created on: Mar 14, 2011
 *      Author: sms103
 */

#include "SFTPConnection.h"

SFTPConnection::SFTPConnection(TCPSocket *sock, bool isActive, ParamParser *paramParser) {
	this->paramParser = paramParser;
	this->active = isActive;
	transpSocket = new SFTPTransportSocket(paramParser, sock,isActive);
	isOpenVar = false;

}

bool SFTPConnection::isActive(){
	return active;
}

void SFTPConnection::clearStats(){
	transpSocket->clearStats();
}

bool SFTPConnection::init(){
	isOpenVar = transpSocket->init();
	return isOpenVar;
}

string SFTPConnection::getDescriptorString(){
	return transpSocket->getDescriptorString();
}

transport_stats * SFTPConnection::getTranspStats(){
	return transpSocket->getTranspStats();

}
network_stats * SFTPConnection::getNetworkStats(){
	return transpSocket->getNetworkStats();
}

bool SFTPConnection::sendMessage(SFTPMessage *msg){
	if(!isOpenVar)return false;
	int bytesSent = 0;
	size_t totalLen = msg->getHeader()->dataLength + sizeof(sftp_message_header);
	//put length and any other multi byte ints in header to net byte order
	msg->toNetByteOrder();

	int retval;
	while(bytesSent < totalLen){
		retval =  transpSocket->transpSend((char *)(msg->mbuf())+bytesSent,totalLen - bytesSent);
		//if something less than or equal to zero is returned our connection is dead.
		if(retval <= 0){
			isOpenVar = false;
			return false;
		}
		bytesSent += retval;
	}
	return true;
}


bool SFTPConnection::recvMessage(SFTPMessage *msg){
	if(!isOpenVar)return false;

	int bytesRcvd = transpSocket->transpRecv(msg->mbuf(),transpSocket->getTransportMSS() - sizeof(STCPHeader));
	if(bytesRcvd <= 0){
		//if something less than or equal to zero is returned our connection is dead.
		isOpenVar = false;
		return false;
	}
	msg->toHostByteOrder();
	return true;
}


uint32_t SFTPConnection::getTransportMSS(){
	return transpSocket->getTransportMSS();
}

void SFTPConnection::close(){
	transpSocket->close();
	isOpenVar = false;
}

bool SFTPConnection::isOpen(){
	return isOpenVar;
}


SFTPConnection::~SFTPConnection() {
	delete(transpSocket);
}
